package cn.szabadsag.hrm.controller;

import cn.szabadsag.hrm.exception.ErrorCode;
import cn.szabadsag.hrm.properties.AliyunOssProperties;
import cn.szabadsag.hrm.util.AjaxResult;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 阿里云对象存储
 * @author yangcong
 * @date 2022年04月07日 19:39
 * @since
 */
@RestController
@RequestMapping("/aliyunoss")
public class AliyunOssController {

    @Autowired
    private AliyunOssProperties properties;

    @GetMapping("/sign")
    public AjaxResult sign() {

        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessId = properties.getAccessKey();
        String accessKey = properties.getSecretKey();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = properties.getEndpoint();
        // 填写Bucket名称，例如examplebucket。
        //String bucket = "examplebucket";
        // 填写Host名称，格式为https://bucketname.endpoint。
        String host = "https://" + properties.getBucketName() + "." + properties.getEndpoint();
        // 设置上传回调URL，即回调服务器地址，用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后，把文件上传信息通过此回调URL发送给应用服务器。
        //String callbackUrl = "https://192.168.0.0:8888";
        // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        String dir = properties.getDir();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));

            return AjaxResult.me().setResultObj(respMap);

        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            e.printStackTrace();
            System.out.println(e.getMessage());
            return AjaxResult.me().setSuccess(false).setCode(ErrorCode.CODE_500_SYSTEM_ERROR.getCode());
        } finally {
            ossClient.shutdown();
        }
    }

    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody Map<String,String> map) {

        System.out.println("需要删除的文件的urlPath：" + map.get("urlPath"));

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = properties.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = properties.getAccessKey();
        String accessKeySecret = properties.getSecretKey();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = properties.getBucketName();
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        String objectName = map.get("urlPath");

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);
            return AjaxResult.me().setSuccess(true).setMessage("操作成功！");
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return AjaxResult.me().setSuccess(false).setMessage("操作失败！");

    }


    /**
     * http://localhost:3010/services/common/aliyunoss/deleteT/?urlPath=images/b0868832-b7c6-4de7-8f7e-54f1b5daa46d_BingWallpaper.jpg
     * urlPath: images/b0868832-b7c6-4de7-8f7e-54f1b5daa46d_BingWallpaper.jpg
     *
     * @param urlPath
     * @return
     */
    @DeleteMapping("/deleteT/{urlPath}")
    public AjaxResult deleteTwo(@PathVariable String urlPath) {
        //  images/b0868832-b7c6-4de7-8f7e-54f1b5daa46d_BingWallpaper.jp
        System.out.println("需要删除的文件的urlPath：" + urlPath);

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = properties.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = properties.getAccessKey();
        String accessKeySecret = properties.getSecretKey();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = properties.getBucketName();
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        String objectName = urlPath;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);
            return AjaxResult.me().setSuccess(true).setMessage("操作成功！");
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return AjaxResult.me().setSuccess(false).setMessage("操作失败！");

    }

}
